package com.blockchain.securewallet.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.adapter.SendRecordAdapter;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.btc.BTCUtils;
import com.blockchain.securewallet.btc.Transaction;
import com.blockchain.securewallet.btc.UnspentOutputInfo;
import com.blockchain.securewallet.dialog.IDialogTipsListener;
import com.blockchain.securewallet.dialog.UniversalDialog;
import com.blockchain.securewallet.interfaces.WalletFields;
import com.blockchain.securewallet.ltc.BCCParams;
import com.blockchain.securewallet.ltc.LTCParams;
import com.blockchain.securewallet.model.SendRecord;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.model.db.UnSpent;
import com.blockchain.securewallet.model.db.dao.DaoSession;
import com.blockchain.securewallet.model.db.dao.FeeSetRecordDao;
import com.blockchain.securewallet.model.db.entity.FeeSetRecord;
import com.blockchain.securewallet.model.db.oper.UnSpentDaoOpe;
import com.blockchain.securewallet.tools.ActivityLauncher;
import com.blockchain.securewallet.tools.TipsWatcher;
import com.blockchain.securewallet.tools.WalletTools;
import com.blockchain.securewallet.utils.EosSignUtil;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.ToMinUtitUtils;
import com.blockchain.securewallet.utils.ToastUtils;
import com.blockchain.securewallet.utils.ToolUtils;
import com.blockchain.securewallet.utils.UIHelper;

import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.script.Script;
import org.json.JSONObject;
import org.spongycastle.util.encoders.Hex;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SendCoinActivity extends BaseActivity implements SendRecordAdapter.IDataChange {
    private static final String TAG = "Wallet.SendRecord";

    public static final int REQUEST_ADDRESS = 1;
    public static final int REQUEST_SCAN = 2;

    public static final String KEY_TYPE_COIN = "key_coin_type";
    public static final String KEY_ADDRESS = "key_address";
    public static final String KEY_POS = "pos";

    public static final String KEY_WALLET_ID = "wallet_id";

    @BindView(R.id.rv_send_record)
    RecyclerView rvRecords;

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.ctl_fee_faq)
    ConstraintLayout ctl_fee_faq;

    @BindView(R.id.cl_fee_select)
    ConstraintLayout cl_fee_select;

    @BindView(R.id.iv_set_fee_default)
    ImageView iv_set_fee_default;

    @BindView(R.id.iv_set_fee_custom)
    ImageView iv_set_fee_custom;

    @BindView(R.id.tv_fee_default)
    TextView tv_fee_default;

    @BindView(R.id.tv_fee_custom)
    TextView tv_fee_custom;

    private boolean isUseDefault = true;

    private SendRecordAdapter adapter;
    private List<SendRecord> records = new ArrayList<>();

    private CoinWallet wallet;
    private int walletId;
    private int type;
    private String title;

    //用于记录手续费设置的选中状态
    private FeeSetRecord fsRecord;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_send_coin);
        ButterKnife.bind(this);
        Intent intent = getIntent();

        if (intent != null) {
            walletId = intent.getIntExtra(KEY_WALLET_ID, 0);

            List<CoinWallet> coinWallets = WalletApp.queryCurrrentWallet();
            if (!ToolUtils.isListEmpty(coinWallets)) {
                wallet = coinWallets.get(walletId);
            }

            if (wallet == null) {
                //终止后面全部程序的进行
                ToastUtils.showToast("Warn:当前钱包为空!");
                return;
            }
        }

        type = wallet.getType();

        //初始化手续费选择的记忆状态
        initFeeSetRecord();
        SendRecord record = new SendRecord();
        switch (type) {
            case CoinWallet.TYPE_BIT_COIN:
                title = String.format(Locale.getDefault(), "%s%s", getString(R.string.wallet_send), getString(R.string.bit_coin_name));
                record.setType(CoinWallet.TYPE_BIT_COIN);
                break;
            case CoinWallet.TYPE_ETH_COIN:
                title = String.format(Locale.getDefault(), "%s%s", getString(R.string.wallet_send), getString(R.string.eth_coin_name));
                record.setType(CoinWallet.TYPE_ETH_COIN);
                break;

            case CoinWallet.TYPE_LTC_COIN:
                title = String.format(Locale.getDefault(), "%s%s", getString(R.string.wallet_send), getString(R.string.ltc_coin_name));
                record.setType(CoinWallet.TYPE_LTC_COIN);
                break;
            case CoinWallet.TYPE_BCH_COIN:
                title = String.format(Locale.getDefault(), "%s%s", getString(R.string.wallet_send), getString(R.string.bch_coin_name));
                record.setType(CoinWallet.TYPE_BCH_COIN);
                break;
            case CoinWallet.TYPE_EOS_COIN:
                title= String.format(Locale.getDefault(), "%s%s", getString(R.string.wallet_send), getString(R.string.eos_coin_name));
                record.setType(CoinWallet.TYPE_EOS_COIN);
                break;

        }

        tvTitle.setText(title);

        this.records.add(record);
        adapter = new SendRecordAdapter(this, this.records);
        rvRecords.setLayoutManager(new LinearLayoutManager(this));
        rvRecords.setAdapter(adapter);
        adapter.setDataChange(this);

        //通过上面的初始化或从数据库获取的，根据币种类型，获得手续费设置记录状态
        if (fsRecord.getIsDefault()) {
            resetUseDefault();
        } else {
            setUseCustom();
        }

        //设置最佳/自定义手续费的显示
        initTradeFeeShow();

        UIHelper.expandViewTouchDelegate(cl_fee_select, 10, 30, 10, 10);
        UIHelper.expandViewTouchDelegate(ctl_fee_faq, 10, 10, 12, 12);
    }

    private void initFeeSetRecord() {
        //查询手续费设置数据库 (不用了，好像不用关掉)   
        DaoSession daoSession = WalletApp.getInstance().getDaoSession();
        FeeSetRecordDao recordDao = daoSession.getFeeSetRecordDao();

        try {
            //当前所有的币种类型记录
            //Logger.ds("come on before...");
            List<FeeSetRecord> records = recordDao.loadAll();
            //Logger.ds("come on after...");

            if (records != null) {
                //如果不存在，则不进入循环
                int count = records.size();
                if (count < 1) {
                    //如果从本地读取的数据库没有记录，则手动添加记录
                    addNewRecord(recordDao, records);

                } else {
                    //至少存在一种币种记录的情况
                    for (int i = 0; i < count; i++) {
                        //目标数据库记录
                        FeeSetRecord record = records.get(i);
                        if (record.getType() == type) {
                            this.fsRecord = record;
                            if (fsRecord == null) {
                                Logger.ds("fsRecord - 我为空");
                            } else {
                                Logger.ds("fsRecord - not null");
                            }
                            //查到就跳出
                            break;
                        }
                    }
                    //如果遍历完毕，还是没有记录，又得主动添加了
                    if (fsRecord == null) {
                        addNewRecord(recordDao, records);
                    }

                }
            } else {
                //查无此数据库
                records = new ArrayList<>();
                //如果从本地读取的数据库没有记录，则手动添加记录
                addNewRecord(recordDao, records);
            }
        } catch (Exception e) {
            // android.database.sqlite.SQLiteException: no such table: FEE_SET_RECORD (code 1): , while compiling: SELECT T."_id",T."TYPE",T."IS_DEFAULT" FROM "FEE_SET_RECORD" T
            Logger.ds("FeeSetRecord err: " + e);
            e.printStackTrace();
        }
    }


    private void addNewRecord(FeeSetRecordDao recordDao, List<FeeSetRecord> records) {
        //没有就要插入新的数据了   
        FeeSetRecord entity = new FeeSetRecord();
        entity.setType(type);
        //第一次创建都是该选择默认的
        entity.setIsDefault(true);

        //避免再次从数据库查询，直接从这里取
        records.add(entity);
        //注意这里的fsRecord没有id
        this.fsRecord = entity;

        if (fsRecord == null) {
            Logger.ds("fsRecord - 我为空");
        } else {
            Logger.ds("fsRecord - not null");
        }

        //为免异常，至少保证前面的有加到
        recordDao.insert(entity);
    }


    private void initTradeFeeShow() {
        //设置手续费显示
        if (wallet.getType() == CoinWallet.TYPE_BIT_COIN) {
            //最佳手续费
            long btcFee = WalletApp.getInstance().getBitCoinFee();
            //这里不能改手续费的单位
            Logger.ds("最佳手续费: " + btcFee);
            BigDecimal btcBig = BigDecimal.valueOf(btcFee).multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(100_000_000));
            tv_fee_default.setText(StringUtil.getResourceStringAndFormat(R.string.fee_trade_btc_optimal, btcBig.toPlainString()));

            showBTCUserFee();

        } else if (wallet.getType() == CoinWallet.TYPE_ETH_COIN) {
            //最佳手续费
            long gasPrice = WalletApp.getInstance().getGasPrice();
            BigDecimal ethBig = BigDecimal.valueOf(gasPrice);       // 单位: Gwei
            //BigDecimal ethBig = BigDecimal.valueOf(gasPrice).divide(BigDecimal.valueOf(1000_000_000));
            tv_fee_default.setText(StringUtil.getResourceStringAndFormat(R.string.fee_trade_eth_optimal, ethBig.toPlainString()));

            showETHUserFee();
        } else if (wallet.getType() == CoinWallet.TYPE_LTC_COIN){
            //最佳手续费
            long ltcFee = WalletApp.getInstance().getLtcCoinFee();
            BigDecimal ltcBig = BigDecimal.valueOf(ltcFee).divide(BigDecimal.valueOf(100_000_000));
            tv_fee_default.setText(StringUtil.getResourceStringAndFormat(R.string.fee_trade_ltc_optimal, ltcBig.toPlainString()));

            showLTCUserFee();
        } else if (wallet.getType() == CoinWallet.TYPE_BCH_COIN){
            //最佳手续费
            long bchFee = WalletApp.getInstance().getBchCoinFee();
            BigDecimal bchBig = BigDecimal.valueOf(bchFee).divide(BigDecimal.valueOf(100_000_000));
            tv_fee_default.setText(StringUtil.getResourceStringAndFormat(R.string.fee_trade_bch_optimal, bchBig.toPlainString()));

            showBCHUserFee();
        }
    }

    private void showBCHUserFee() {
        //自定义手续费
        String fee = StringUtil.getResourceStringAndFormat(R.string.fee_trade_bch_custom, WalletTools.getUserBCHFee());
        tv_fee_custom.setText(fee);
    }

    private void showLTCUserFee() {
        //自定义手续费
        String fee = StringUtil.getResourceStringAndFormat(R.string.fee_trade_ltc_custom, WalletTools.getUserLTCFee());
        tv_fee_custom.setText(fee);
    }


    private void showETHUserFee() {
        String userETHFee = WalletTools.getUserETHFee();
        Logger.ds("自定义ETH手续费: " + userETHFee);
        //自定义手续费
        tv_fee_custom.setText(StringUtil.getResourceStringAndFormat(R.string.fee_trade_eth_custom, userETHFee));
        //BigDecimal ethUserBig = BigDecimal.valueOf(ethUserFee).divide(BigDecimal.valueOf(1000_000_000));
        //tv_fee_custom.setText(StringUtil.getResourceStringAndFormat(R.string.fee_trade_optimal_eth, ethUserBig.toPlainString()));
    }

    private void showBTCUserFee() {
        //自定义手续费
        String fee = StringUtil.getResourceStringAndFormat(R.string.fee_trade_btc_custom, WalletTools.getUserBTCFee());
        tv_fee_custom.setText(fee);
    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }


    @OnClick({R.id.cl_fee_select})
    void set_fee_default() {
        //根据当前按钮状态切换模式
        if (iv_set_fee_default.getTag().equals("1")) {
            //设置为自定义手续费
            setNoUseDefault();

        } else if (iv_set_fee_default.getTag().equals("2")) {
            //设置为最佳手续费
            resetUseDefault();
        }
    }


    //@OnClick(R.id.tv_set_fee)
    void set_fee() {

        if (wallet.getType() == CoinWallet.TYPE_BIT_COIN) {
            feeSetForBTC();

        } else if (wallet.getType() == CoinWallet.TYPE_ETH_COIN) {
            feeSetForETH();
        } else if (wallet.getType() == CoinWallet.TYPE_LTC_COIN){
            feeSetForLTC();
        } else if (wallet.getType() == CoinWallet.TYPE_BCH_COIN){
            feeSetForBCH();
        }

    }

    private void feeSetForBCH() {
        UniversalDialog dialog = UniversalDialog.showBchFeeDialog(getSupportFragmentManager(), new IDialogTipsListener() {
            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 1) {
                    return;
                }

                // Logger.ds(">> 输入的: " + texts[0]);

                if (!TextUtils.isEmpty(texts[0])) {
                    try {
                        // BTC/KB   //这里除以KB就是除以1000了   //取消除以1000，然后在别的地方，就要取消乘以1000了
                        BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(texts[0])).multiply(BigDecimal.valueOf(100_000_000));
                        //BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(texts[0])).multiply(BigDecimal.valueOf(100_000_000)).divide(BigDecimal.valueOf(1000));
                        long value = bigDecimal.longValue();
                        String str = bigDecimal.toString();
                        //Logger.ds("btc value: " + value + "\t\t> btc str: " + str);
                        WalletApp.getInstance().saveUserLtcFee(value);

                        //与选择状态的记录同步 - 自定义
                        updateSelectedState(false);

                        //设置是自定义的手续费
                        setUseCustom();
                        //刷新自定义手续费的显示
                        showBCHUserFee();

                    } catch (Exception e) {
                        Logger.ds("trade fee set err: " + e.getMessage());
                    }

//                    long btcFee = WalletApp.getInstance().getBitCoinFee();
//                    BigDecimal btcBig = BigDecimal.valueOf(btcFee).multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(100_000_000));

                } else {
                    ToastUtils.showToast("手续费金额不能为空");
                    resetUseDefault();
                }
            }
        }, WalletTools.getUserBCHFee());
    }

    private void feeSetForLTC() {
        UniversalDialog dialog = UniversalDialog.showLtcFeeDialog(getSupportFragmentManager(), new IDialogTipsListener() {
            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 1) {
                    return;
                }

                // Logger.ds(">> 输入的: " + texts[0]);

                if (!TextUtils.isEmpty(texts[0])) {
                    try {
                        // BTC/KB   //这里除以KB就是除以1000了   //取消除以1000，然后在别的地方，就要取消乘以1000了
                        BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(texts[0])).multiply(BigDecimal.valueOf(100_000_000));
                        //BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(texts[0])).multiply(BigDecimal.valueOf(100_000_000)).divide(BigDecimal.valueOf(1000));
                        long value = bigDecimal.longValue();
                        String str = bigDecimal.toString();
                        //Logger.ds("btc value: " + value + "\t\t> btc str: " + str);
                        WalletApp.getInstance().saveUserLtcFee(value);

                        //与选择状态的记录同步 - 自定义
                        updateSelectedState(false);

                        //设置是自定义的手续费
                        setUseCustom();
                        //刷新自定义手续费的显示
                        showLTCUserFee();

                    } catch (Exception e) {
                        Logger.ds("trade fee set err: " + e.getMessage());
                    }

//                    long btcFee = WalletApp.getInstance().getBitCoinFee();
//                    BigDecimal btcBig = BigDecimal.valueOf(btcFee).multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(100_000_000));

                } else {
                    ToastUtils.showToast("手续费金额不能为空");
                    resetUseDefault();
                }
            }
        }, WalletTools.getUserLTCFee());
    }

    private void feeSetForETH() {

        UniversalDialog dialog = UniversalDialog.showEthFeeDialog(getSupportFragmentManager(), new IDialogTipsListener() {

            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 3) {
                    return;
                }

                if (!TextUtils.isEmpty(texts[2])) {
                    try {
                        long nonce = BigDecimal.valueOf(Double.valueOf(texts[2])).longValue();
                        WalletApp.getInstance().saveUserNonce(nonce);
                    } catch (Exception e) {
                        Log.i("ywLog", "nonce illegal", e);
                    }
                }
                if (!TextUtils.isEmpty(texts[0])) {
                    try {
                        long price = BigDecimal.valueOf(Double.valueOf(texts[0])).longValue();
                        Logger.ds("eth value: " + price);
                        WalletApp.getInstance().saveUserGasPrice(price);

                        //与选择状态的记录同步 - 自定义
                        updateSelectedState(false);

                        //设置是自定义的手续费
                        setUseCustom();
                        //刷新自定义手续费的显示
                        showETHUserFee();

                    } catch (Exception e) {
                        Log.i("ywLog", "gas illegal", e);
                    }
                } else {
                    ToastUtils.showToast("Gas Price不能为空");
                    resetUseDefault();
                }

                if (!TextUtils.isEmpty(texts[1])) {
                    try {
                        long limit = BigDecimal.valueOf(Double.valueOf(texts[1])).longValue();
                        WalletApp.getInstance().saveUserGasLimit(limit);
                    } catch (Exception e) {
                        Log.i("ywLog", "gasLimit illegal", e);
                    }
                }
            }

        }, WalletTools.getUserETHFee(), WalletTools.getETHGasLimit(), WalletTools.getETHNonce());
    }

    private void feeSetForBTC() {

        UniversalDialog dialog = UniversalDialog.showBtcFeeDialog(getSupportFragmentManager(), new IDialogTipsListener() {
            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 1) {
                    return;
                }

                // Logger.ds(">> 输入的: " + texts[0]);

                if (!TextUtils.isEmpty(texts[0])) {
                    try {
                        // BTC/KB   //这里除以KB就是除以1000了   //取消除以1000，然后在别的地方，就要取消乘以1000了
                        BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(texts[0])).multiply(BigDecimal.valueOf(100_000_000));
                        //BigDecimal bigDecimal = BigDecimal.valueOf(Double.valueOf(texts[0])).multiply(BigDecimal.valueOf(100_000_000)).divide(BigDecimal.valueOf(1000));
                        long value = bigDecimal.longValue();
                        String str = bigDecimal.toString();
                        //Logger.ds("btc value: " + value + "\t\t> btc str: " + str);
                        WalletApp.getInstance().saveUserBitCoinFee(value);

                        //与选择状态的记录同步 - 自定义
                        updateSelectedState(false);

                        //设置是自定义的手续费
                        setUseCustom();
                        //刷新自定义手续费的显示
                        showBTCUserFee();

                    } catch (Exception e) {
                        Logger.ds("trade fee set err: " + e.getMessage());
                    }

//                    long btcFee = WalletApp.getInstance().getBitCoinFee();
//                    BigDecimal btcBig = BigDecimal.valueOf(btcFee).multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(100_000_000));

                } else {
                    ToastUtils.showToast("手续费金额不能为空");
                    resetUseDefault();
                }
            }
        }, WalletTools.getUserBTCFee());
    }


    private void updateSelectedState(Boolean isDefault) {
        //这里选择成功，那就在这里更新相应币种手续费的选择状态
        DaoSession daoSession = WalletApp.getInstance().getDaoSession();
        FeeSetRecordDao recordDao = daoSession.getFeeSetRecordDao();
        //Logger.ds("准备更新选中状态");

        //因为在onCreate中，我们进行了初始化，所以这里不存在没有数据库的问题，就不用另作判断
        //---方法1
        //遍历查找
        /*List<FeeSetRecord> records = recordDao.loadAll();
        for (int i = 0; i < records.size(); i++) {
            //每个币种，只有1条记录
            FeeSetRecord record = records.get(i);
            if (record.getType() == fsRecord.getType()) {
                FeeSetRecord entity = new FeeSetRecord();
                entity.setId(record.getId());
                entity.setType(record.getType());
                //既然选中了自定义，那么就不是默认的了
                entity.setIsDefault(false);
                Logger.ds("更新选中状态为自定义");
                recordDao.update(entity);
                break;
            }
        }*/

        //---方法2
        //直接查找
        List<FeeSetRecord> list = recordDao.queryBuilder().where(FeeSetRecordDao.Properties.Type.eq(fsRecord.getType())).list();
        FeeSetRecord model = list.get(0);
        if (model == null) {
            Logger.ds("查无此库！");
            return;
        }
        //Logger.ds("更新选中状态为自定义");
        //false为自定义，true为最佳手续费
        model.setIsDefault(isDefault);
        recordDao.update(model);
        
        /*List<FeeSetRecord> all = recordDao.loadAll();
        for (int i = 0; i < all.size(); i++) {
            FeeSetRecord fsr = all.get(i);
            Logger.ds("record: " + fsr.getId() + "\t\t" + fsr.getType() + "\t\t" + fsr.getIsDefault());
        }*/
    }


    private void setNoUseDefault() {
        iv_set_fee_default.setTag("2");
        iv_set_fee_default.setImageResource(R.drawable.ic_unselected);
        isUseDefault = false;

        //上面的不选中就换成下面的被选中
        iv_set_fee_custom.setImageResource(R.drawable.ic_selected);

        //调用设置金额的方法
        set_fee();
    }

    private void resetUseDefault() {
        iv_set_fee_default.setTag("1");
        iv_set_fee_default.setImageResource(R.drawable.ic_selected);
        isUseDefault = true;

        //上面的不选中就换成下面的被选中
        iv_set_fee_custom.setImageResource(R.drawable.ic_unselected);

        //更新数据库，将选中类型改为默认的最佳手续费
        //与选择状态的记录同步 - 自定义
        updateSelectedState(true);
    }

    private void setUseCustom() {
        iv_set_fee_default.setTag("2");
        iv_set_fee_default.setImageResource(R.drawable.ic_unselected);
        isUseDefault = false;

        //上面的不选中就换成下面的被选中
        iv_set_fee_custom.setImageResource(R.drawable.ic_selected);
    }

    @OnClick(R.id.ctl_fee_faq)
    void go_to_faq() {
        //ToastUtils.showToast("FAQ");
        //ActivityLauncher.gotoFAQActivity(this);
        ActivityLauncher.gotoFAQDetailsActivity(this, WalletFields.FAQ.FEE_SET);
    }


    @Override
    public void onScan(int pos) {
        requestByScan(pos);
    }

    @Override
    public void onOpenBook(int pos) {
        requestAddress(pos);
    }

    @Override
    public void onDelete(int pos) {
        records.remove(pos);
        adapter.notifyItemRangeRemoved(pos, 1);
        adapter.notifyItemRangeChanged(pos, adapter.getItemCount() - pos);
    }

    @Override
    public void onAddressChange(int pos, String address) {
        SendRecord record = records.get(pos);
        record.setAddress(address);
    }

    @Override
    public void onValueChange(int pos, String value) {
        SendRecord record = records.get(pos);
        record.setValue(value);

        Logger.ds("当前: " + pos + "\t\t金额: " + record.getValue());
    }

    @Override
    public void onUnitChange(int pos, int unit) {
        SendRecord record = records.get(pos);
        record.setUnit(unit);
    }

    @Override
    public void onAddRecord() {
        if (wallet.getType() == CoinWallet.TYPE_ETH_COIN && records.size() >= 1)
            return;

        SendRecord record = new SendRecord();
        record.setType(wallet.getType() == CoinWallet.TYPE_BIT_COIN ? SendRecord.TYPE_BIT_COIN : SendRecord.TYPE_ETH_COIN);
        records.add(record);

        //"新增按钮"也是一个item
        adapter.notifyItemInserted(records.size() - 1);
        //rvRecords.scrollToPosition(records.size()-1);
        rvRecords.smoothScrollToPosition(records.size());
        //adapter.notifyItemRangeChanged(0, adapter.getItemCount());
        //adapter.notifyDataSetChanged();
    }


    @OnClick(R.id.btn_ensure)
    void generateTransaction() {

        Log.i("redrear", records.get(0).getAddress() + "test");

        for (int i = 0; i < records.size(); i++) {
            //校验输入信息    // 当前的记录对象
            SendRecord sr = records.get(i);
            String trimAddress = sr.getAddress().trim();
            String trimValue = sr.getValue().trim();
            Logger.ds("trimAddress: " + trimAddress + "\t\t\t" + "trimValue: " + trimValue);

            if (StringUtil.isEmpty(trimAddress)) {
                ToastUtils.showToast("请输入地址");
                return;
            }

            //校验地址  //不是正确的地址  //测试停用
            if (!ToolUtils.isCorrectAddress(sr.getAddress().trim())) {
                //地址格式不正确
                ToastUtils.showToast("地址格式不正确");
                return;
            }
            
            if (StringUtil.isEmpty(trimValue)) {
                ToastUtils.showToast("请输入金额");
                return;
            }

            String money = sr.getValue();
            if (ToolUtils.lastPointJudge(money)) {
                ToastUtils.showToast("最后一位不能为小数点");
                return;
            }

            //对自身的遍历
            for (int j = 0; j < records.size(); j++) {
                if (records.get(j).getAddress().trim().equals(sr.getAddress().trim())) {
                    if (i != j) {
                        ToastUtils.showToast("当前列表不能包含相同的地址");
                        return;
                    }
                }
            }
            Logger.ds(">> 第" + i + "轮");
        }

        //校验余额
        //转账金额
        BigInteger amountToSend = new BigInteger("0");
        if (records.get(0).getType() == 0) {
            Logger.ds("btc -- ");
            for (int postion = 0; postion < records.size(); postion++) {
                int unit = records.get(postion).getUnit();
                String value = records.get(postion).getValue();
                Logger.ds(">> unit: " + unit + ">> 金额: " + value);
                amountToSend = amountToSend.add(ToMinUtitUtils.btcConvertToMin(unit, value));
            }
        } else if (records.get(0).getType() == 1) {
            Logger.ds("eth -- ");
            //eth
            amountToSend = ToMinUtitUtils.ethConvertToMin(records.get(0).getUnit(), records.get(0).getValue());
        }

        //补充单位校验
        int compareResult = amountToSend.compareTo(new BigInteger(wallet.getValue() + ""));

        if (wallet.getValue() == 0 || compareResult > 0) {
            ToastUtils.showToast("当前余额不足");
            return;
        }

        UniversalDialog dialog = UniversalDialog.showPayDialog(getSupportFragmentManager(), new IDialogTipsListener() {
            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 1) {
                    Logger.ds("不是1项");
                    return;
                }
                Logger.ds("continue");

                final TextView tv_err = view.findViewById(R.id.tv_tips_pw_err);
                EditText edit_first_pw = view.findViewById(R.id.edit_first_password);

                TipsWatcher watcher = new TipsWatcher(tv_err);
                edit_first_pw.addTextChangedListener(watcher);

                if (TextUtils.isEmpty(texts[0])) {
                    tv_err.setText("*密码不能为空");
                    tv_err.setVisibility(View.VISIBLE);

                } else if (texts[0].length() < 5) {
                    tv_err.setText("*密码长度不能小于5位");
                    tv_err.setVisibility(View.VISIBLE);

                } else if (!texts[0].equals(WalletApp.getInstance().getPayPassword())) {
                    tv_err.setText("*密码错误");
                    tv_err.setVisibility(View.VISIBLE);

                } else {
                    String signText = generateSignTransaction();
                    Log.i("ltcsign", signText);
                    if (TextUtils.isEmpty(signText)) {
                        Toast.makeText(SendCoinActivity.this, "签名生成失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent intent = new Intent();
                    intent.setClass(SendCoinActivity.this, TransactionActivity.class);
                    intent.putExtra(TransactionActivity.KEY_WALLET_ID, walletId);
                    intent.putExtra(TransactionActivity.KEY_TRANSACTION, signText);
                    startActivity(intent);
                }
            }
        });

    }

    private String generateSignTransaction() {
        if (wallet.getType() == CoinWallet.TYPE_BIT_COIN) {
            return generateBitCoinSignTransaction();
        } else if (wallet.getType() == CoinWallet.TYPE_ETH_COIN) {
            return generateEtherSignTransAction();
        } else if (wallet.getType() == CoinWallet.TYPE_LTC_COIN) {
            return generateTestLtcCoinSignTransaction();
        } else if (wallet.getType() == CoinWallet.TYPE_BCH_COIN){
////            return generateLtcCoinSignTransaction();
//            List<UnSpent> unSpents=new ArrayList<>();
//            UnSpent unSpent=new UnSpent();
//            unSpent.setAddress("1FuG1uDvAzCbj4bKkm87kjwRFXhFjAAUi9");
////            unSpent.setAddress("qz3h8m8pvvxxdsnguqnk25dnm9ex5xad2qw8qtxw9w");
//            unSpent.setTxid("548908f42769f31ab519ebcf28fe4135a7c9cb8c806d95037be966d5d754b40f");
//            unSpent.setOutputNo(0);
//            unSpent.setValue(1876000);
//            unSpent.setConfirmations(1);
//            unSpent.setScript("76a914a373ece1630c66c268e0276551b3d9726a1bad5088ac");
////            unSpent.setScript("76a91403cf011c9c9074e4c3a9ecfaac774044f0eb1ec388ac");
//            unSpents.add(unSpent);

//            return generateTestBchCoinSignTransaction2(unSpents,1000L,208000L,"1F3mjTZdDK7dXnhbK9VBYTDa57n6GumB77");
            return generateTestBchCoinSignTransaction();
//            return generateBitCoinSignTransaction();
//            return generateTestBchCoinSignTransaction(unSpents,1000L,208000L,"qzdp0mhdac0rul5u76cla77zftr0x2s60y3gl5k2qp");
        } else if (wallet.getType() == CoinWallet.TYPE_EOS_COIN) {
//            return generateLtcCoinSignTransaction();
            List<UnSpent> unSpents = new ArrayList<>();
            UnSpent unSpent = new UnSpent();
            unSpent.setAddress("LKa6Ghh74fR6Z9ororb2sLetdx6F7ZsXcg");
            unSpent.setTxid("af98a17f8248033f90aa2915599509a25387c12940e01e7591ad4f387eaec153");
            unSpent.setOutputNo(0);
            unSpent.setValue(10900000);
            unSpent.setConfirmations(1168);
            unSpent.setScript("76a91403cf011c9c9074e4c3a9ecfaac774044f0eb1ec388ac");
            unSpents.add(unSpent);

            return generateTestEosCoinSignTransaction(unSpents,1000L,208000L,"1AZRNsXr3FcihgSZ4QfemAv81DakadT4La");
        }
        else{
            return null;
        }
    }

    private String generateTestBchCoinSignTransaction() {

        List<UnSpent> unSpentList = UnSpentDaoOpe.queryDateFromAddress(this, wallet.getAddress());

        List<SendRecord> okRecords = new ArrayList<>();
        for (SendRecord record : records) {
            if (TextUtils.isEmpty(record.getAddress()) || TextUtils.isEmpty(record.getValue())) {
                continue;
            }
            okRecords.add(record);
        }
        if (okRecords.size() == 0)
            return "";

        BigDecimal bigDecimal = new BigDecimal(okRecords.get(0).getValue());
        bigDecimal = bigDecimal.multiply(new BigDecimal(100_000_000));
        Long value = bigDecimal.longValue();
        long fee = 0L;
        if (isUseDefault) {
            fee = WalletApp.getInstance().getBchCoinFee();
            Logger.ds("使用默认的手续费: " + fee + " 聪/KB");
        } else {
            long tmp = WalletApp.getInstance().getUserBchFee();
            //前面的没有除以1000，除以1000的单位才是 LTC/KB
            BigDecimal ltcBig = BigDecimal.valueOf(tmp);
            //小于整数则不为0了
            //fee = btcBig.longValue();
            fee = ltcBig.longValue();
            Logger.ds("使用自定义的手续费: " + fee + " 聪/KB");
        }


        String address = okRecords.get(0).getAddress();


        BCCParams bchParams = BCCParams.get();
        //传入主网参数
        org.bitcoinj.core.Transaction transaction = new org.bitcoinj.core.Transaction(bchParams);
        Long money = 0L;
        List<UnSpent> utxos = new ArrayList<>();
        //遍历unspents, 组装合适的item

        for (int i = 0; i < unSpentList.size(); i++) {
            if (money >= (value + fee)) {
                break;
            }
            utxos.add(unSpentList.get(i));
            money += unSpentList.get(i).getValue();
        }
        transaction.addOutput(Coin.valueOf(value), Address.fromBase58(bchParams, address));
//        transaction.addOutput(Coin.valueOf(value), Address.fromBase58(bchParams, utxos.get(0).getScript()));
        Long leave = money - value - fee;
        if (leave > 0) {
            transaction.addOutput(Coin.valueOf(leave), Address.fromBase58(bchParams, wallet.getAddress()));
        }

        for (int i = 0; i < utxos.size(); i++) {
//            TransactionOutPoint outPoint = new TransactionOutPoint(ltcParams, utxos.get(i).getIndex(), Sha256Hash.wrap(utxos.get(i).getTxid()));
            TransactionOutPoint outPoint = new TransactionOutPoint(bchParams, utxos.get(i).getOutputNo(), Sha256Hash.wrap(utxos.get(i).getTxid()));
            Script script = new Script(BTCUtils.fromHex(utxos.get(i).getScript()));
//            Script script = new Script(BTCUtils.fromHex("76a91403cf011c9c9074e4c3a9ecfaac774044f0eb1ec388ac"));
//            Transaction.Script script = new Transaction.Script(BTCUtils.fromHex(utxos.get(i).getScript()));
            ECKey ecKey = ECKey.fromPrivate(Hex.decode(wallet.getSeed()));
//            transaction.addSignedInput(outPoint, script, ecKey, org.bitcoinj.core.Transaction.SigHash.ALL, true);
            transaction.addSignedInput(outPoint, script, ecKey, org.bitcoinj.core.Transaction.SigHash.ALL, true);
//            transaction.addSignedInput(outPoint, script, ecKey, org.bitcoinj.core.Transaction.SigHash.SINGLE, true);

        }
        return BTCUtils.toHex(transaction.bitcoinSerialize());


    }

    private String generateTestEosCoinSignTransaction(List<UnSpent> unSpents, long l, long l1, String s) {


        try {
            return EosSignUtil.transfer(wallet.getPrivateKey(),"espritblocke", "inita","initb", "12.2821 MSP", "备注");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "shibai";


    }

    private String generateTestBchCoinSignTransaction2(List<UnSpent> unSpentList, //未消费列表
                                                      Long value, //需要转账的值
                                                      Long fee, //矿工费
                                                      String address//转账地址
    ) {

        NetworkParameters bchParams = BCCParams.get();
        //传入主网参数
        org.bitcoinj.core.Transaction transaction = new org.bitcoinj.core.Transaction(bchParams);
        Long money = 0L;
        List<UnSpent> utxos = new ArrayList<>();
        //遍历unspents, 组装合适的item
        for (int i = 0; i < unSpentList.size(); i++) {
            if (money >= (value + fee)) {
                break;
            }
            utxos.add(unSpentList.get(i));
            money += unSpentList.get(i).getValue();
        }
        transaction.addOutput(Coin.valueOf(value), Address.fromBase58(bchParams, address));
        Long leave = money - value - fee;
        if (leave > 0) {
            transaction.addOutput(Coin.valueOf(leave), Address.fromBase58(bchParams, wallet.getAddress()));
        }
        for (int i = 0; i < utxos.size(); i++) {
            TransactionOutPoint outPoint = new TransactionOutPoint(bchParams, utxos.get(i).getOutputNo(), Sha256Hash.wrap(utxos.get(i).getTxid()));
            Script script = new Script(BTCUtils.fromHex(utxos.get(i).getScript()));
//            Transaction.Script script = new Transaction.Script(BTCUtils.fromHex(utxos.get(i).getScript()));
            ECKey ecKey = ECKey.fromPrivate(Hex.decode(wallet.getSeed()));
            transaction.addSignedInput(outPoint, script, ecKey, org.bitcoinj.core.Transaction.SigHash.ALL, true);

        }
        return BTCUtils.toHex(transaction.bitcoinSerialize());

    }

    private String generateTestLtcCoinSignTransaction() {

        List<UnSpent> unSpentList = UnSpentDaoOpe.queryDateFromAddress(this, wallet.getAddress());

        List<SendRecord> okRecords = new ArrayList<>();
        for (SendRecord record : records) {
            if (TextUtils.isEmpty(record.getAddress()) || TextUtils.isEmpty(record.getValue())) {
                continue;
            }
            okRecords.add(record);
        }
        if (okRecords.size() == 0)
            return "";

        BigDecimal bigDecimal = new BigDecimal(okRecords.get(0).getValue());
        bigDecimal = bigDecimal.multiply(new BigDecimal(100_000_000));
        Long value = bigDecimal.longValue();
        long fee = 0L;
        if (isUseDefault) {
            fee = WalletApp.getInstance().getLtcCoinFee();
            Logger.ds("使用默认的手续费: " + fee + " 聪/KB");
        } else {
            long tmp = WalletApp.getInstance().getUserLtcFee();
            //前面的没有除以1000，除以1000的单位才是 LTC/KB
            BigDecimal ltcBig = BigDecimal.valueOf(tmp);
            //小于整数则不为0了
            //fee = btcBig.longValue();
            fee = ltcBig.longValue();
            Logger.ds("使用自定义的手续费: " + fee + " 聪/KB");
        }


        String address = okRecords.get(0).getAddress();


        LTCParams ltcParams = LTCParams.get();
        //传入主网参数
        org.bitcoinj.core.Transaction transaction = new org.bitcoinj.core.Transaction(ltcParams);
        Long money = 0L;
        List<UnSpent> utxos = new ArrayList<>();
        //遍历unspents, 组装合适的item

        for (int i = 0; i < unSpentList.size(); i++) {
            if (money >= (value + fee)) {
                break;
            }
            utxos.add(unSpentList.get(i));
            money += unSpentList.get(i).getValue();
        }
        transaction.addOutput(Coin.valueOf(value), Address.fromBase58(ltcParams, address));
        Long leave = money - value - fee;
        if (leave > 0) {
            transaction.addOutput(Coin.valueOf(leave), Address.fromBase58(ltcParams, wallet.getAddress()));
        }

        for (int i = 0; i < utxos.size(); i++) {
//            TransactionOutPoint outPoint = new TransactionOutPoint(ltcParams, utxos.get(i).getIndex(), Sha256Hash.wrap(utxos.get(i).getTxid()));
            TransactionOutPoint outPoint = new TransactionOutPoint(ltcParams, utxos.get(i).getOutputNo(), Sha256Hash.wrap(utxos.get(i).getTxid()));
            Script script = new Script(BTCUtils.fromHex(utxos.get(i).getScript()));
//            Transaction.Script script = new Transaction.Script(BTCUtils.fromHex(utxos.get(i).getScript()));
            ECKey ecKey = ECKey.fromPrivate(Hex.decode(wallet.getSeed()));
            transaction.addSignedInput(outPoint, script, ecKey, org.bitcoinj.core.Transaction.SigHash.ALL, true);

        }
        return BTCUtils.toHex(transaction.bitcoinSerialize());
//        return Hex.toHexString(transaction.bitcoinSerialize());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String result = data.getStringExtra(KEY_ADDRESS);
            String address = null;
            String value = null;
            try {
                JSONObject jsonObject = new JSONObject(result);
                address = jsonObject.getString("a");
                value = jsonObject.optString("v");
            } catch (Exception e) {
                address = result;
            }

            int pos = data.getIntExtra(KEY_POS, -1);
            if (!TextUtils.isEmpty(address) && pos != -1) {
                SendRecord record = records.get(pos);
                record.setAddress(address);
                if (!TextUtils.isEmpty(value)) {
                    BigDecimal bigValue = null;
                    if (record.getType() == SendRecord.TYPE_BIT_COIN) {
                        bigValue = BigDecimal.valueOf(Double.parseDouble(value)).divide(BigDecimal.valueOf(100_000_000));
                    } else {
                        bigValue = Convert.fromWei(value, Convert.Unit.ETHER);
                    }
                    record.setValue(bigValue.doubleValue() + "");
                }
                adapter.notifyItemChanged(pos);
            }
        }
    }


    private void requestAddress(int pos) {
        int type = wallet.getType();
        Intent intent = new Intent();
        intent.putExtra(KEY_TYPE_COIN, type);
        intent.putExtra(KEY_POS, pos);
        intent.setClass(this, AddressBookActivity.class);
        startActivityForResult(intent, pos);
    }

    private void requestByScan(int pos) {
        int type = wallet.getType();
        Intent intent = new Intent();
        intent.putExtra(KEY_TYPE_COIN, type);
        intent.putExtra(KEY_POS, pos);
        intent.putExtra(QrCodeScanActivity.KEY_MODULE_FROM, QrCodeScanActivity.MODULE_SEND_COIN);
        intent.setClass(this, QrCodeScanActivity.class);
        startActivityForResult(intent, pos);
    }

    private String generateBitCoinSignTransaction() {
        byte[] seeds = Hex.decode(wallet.getSeed());
        com.blockchain.securewallet.btc.KeyPair keyPair = BTCUtils.generateWifKey(false, CoinWallet.BIT_COIN_WALLET_TYPE, seeds);
        ArrayList<UnspentOutputInfo> unspentOutputs = new ArrayList<>();
//        List<UnSpent> unSpents = WalletApp.getInstance().getDaoSession().loadAll(UnSpent.class);
        List<UnSpent> unSpents = UnSpentDaoOpe.queryDateFromAddress(this, wallet.getAddress());
        for (UnSpent u : unSpents) {
            byte[] txHash = BTCUtils.fromHex(u.getTxid());
            Transaction.Script script = new Transaction.Script(BTCUtils.fromHex(u.getScript()));
            long value = u.getValue();
            int outputIndex = u.getOutputNo();
            unspentOutputs.add(new UnspentOutputInfo(keyPair, txHash, script, value, outputIndex));
        }

        List<SendRecord> okRecords = new ArrayList<>();
        for (SendRecord record : records) {
            if (TextUtils.isEmpty(record.getAddress()) || TextUtils.isEmpty(record.getValue())) {
                continue;
            }
            okRecords.add(record);
        }
        if (okRecords.size() == 0)
            return "";

//        String to = "15jeFJ2LUaUoaZrz8nrqYBkteZZKSrQu2p";

//        byte[] seeds= Hex.decode("4c1f97e603e7e1ea0c93886cb7299adb02789246f9aeb1f195c3136ea0e7291b");
//        com.blockchain.securewallet.btc.KeyPair keyPair = BTCUtils.generateWifKey(false, CoinWallet.BIT_COIN_WALLET_TYPE,seeds);
//        ArrayList<UnspentOutputInfo> unspentOutputs = new ArrayList<>();
//        byte[] txHash = BTCUtils.reverse(BTCUtils.fromHex("523312544fd94beeeb4a08127a58cd2f4e412795747759f5ad06216fa85b6d14"));
//        Transaction.Script script = new Transaction.Script(BTCUtils.fromHex("76a914094809350f056628fd9e0011e45253f2033921fc88ac"));
//        long value = 50000;
//        int outputIndex = 0;
//        unspentOutputs.add(new UnspentOutputInfo(keyPair, txHash, script, value, outputIndex));
        //long fee;
        float fee;

        if (isUseDefault) {
            fee = WalletApp.getInstance().getBitCoinFee();
            Logger.ds("使用默认的手续费: " + fee + " 聪/KB");
        } else {
            long tmp = WalletApp.getInstance().getUserBitCoinFee();
            //前面的没有除以1000，除以1000的单位才是 BTC/KB
            BigDecimal btcBig = BigDecimal.valueOf(tmp).divide(BigDecimal.valueOf(1000));
            //小于整数则不为0了
            //fee = btcBig.longValue(); 
            fee = btcBig.floatValue();
            Logger.ds("使用自定义的手续费: " + fee + " 聪/KB");
        }

        String signText = wallet.signedBitCoinMultiTransactionData(unspentOutputs, okRecords, fee, BTCUtils.TRANSACTION_TYPE_SEGWIT);
        Log.i(TAG, "signText:" + signText);
        return signText;
    }

    private String generateLtcCoinSignTransaction() {
        byte[] seeds = Hex.decode(wallet.getSeed());
        com.blockchain.securewallet.btc.KeyPair keyPair = BTCUtils.generateWifKey(false, CoinWallet.BIT_COIN_WALLET_TYPE, seeds);
        ArrayList<UnspentOutputInfo> unspentOutputs = new ArrayList<>();
//        List<UnSpent> unSpents = WalletApp.getInstance().getDaoSession().loadAll(UnSpent.class);
//        List<UnSpent> unSpents = UnSpentDaoOpe.queryDateFromAddress(this, wallet.getAddress());
        List<UnSpent> unSpents = new ArrayList<>();
        UnSpent unSpent = new UnSpent();
        unSpent.setAddress("LKa6Ghh74fR6Z9ororb2sLetdx6F7ZsXcg");
        unSpent.setTxid("af98a17f8248033f90aa2915599509a25387c12940e01e7591ad4f387eaec153");
        unSpent.setOutputNo(0);
        unSpent.setValue(10900000);
        unSpent.setConfirmations(2);
        unSpent.setScript("76a91403cf011c9c9074e4c3a9ecfaac774044f0eb1ec388ac");
        unSpents.add(unSpent);


        for (UnSpent u : unSpents) {
            byte[] txHash = BTCUtils.fromHex(u.getTxid());
            Transaction.Script script = new Transaction.Script(BTCUtils.fromHex(u.getScript()));
            long value = u.getValue();
            int outputIndex = u.getOutputNo();
            unspentOutputs.add(new UnspentOutputInfo(keyPair, txHash, script, value, outputIndex));
        }

        List<SendRecord> okRecords = new ArrayList<>();
        for (SendRecord record : records) {
            if (TextUtils.isEmpty(record.getAddress()) || TextUtils.isEmpty(record.getValue())) {
                continue;
            }
            okRecords.add(record);
        }
        if (okRecords.size() == 0)
            return "";

//        String to = "15jeFJ2LUaUoaZrz8nrqYBkteZZKSrQu2p";

//        byte[] seeds= Hex.decode("4c1f97e603e7e1ea0c93886cb7299adb02789246f9aeb1f195c3136ea0e7291b");
//        com.blockchain.securewallet.btc.KeyPair keyPair = BTCUtils.generateWifKey(false, CoinWallet.BIT_COIN_WALLET_TYPE,seeds);
//        ArrayList<UnspentOutputInfo> unspentOutputs = new ArrayList<>();
//        byte[] txHash = BTCUtils.reverse(BTCUtils.fromHex("523312544fd94beeeb4a08127a58cd2f4e412795747759f5ad06216fa85b6d14"));
//        Transaction.Script script = new Transaction.Script(BTCUtils.fromHex("76a914094809350f056628fd9e0011e45253f2033921fc88ac"));
//        long value = 50000;
//        int outputIndex = 0;
//        unspentOutputs.add(new UnspentOutputInfo(keyPair, txHash, script, value, outputIndex));
        long fee;
        if (isUseDefault) {
            fee = WalletApp.getInstance().getBitCoinFee();
        } else {
            fee = WalletApp.getInstance().getUserBitCoinFee();
        }

        String signText = wallet.signedLtcCoinTransactionData(unspentOutputs, okRecords, fee, BTCUtils.TRANSACTION_TYPE_SEGWIT);
        Log.i(TAG, "signText:" + signText);
        return signText;
    }


    private String generateEtherSignTransAction() {
        if (records.size() < 1)
            return "";
        String signText;
        SendRecord record = records.get(0);
        String to = record.getAddress();
        String value = record.getValue();
        if (TextUtils.isEmpty(to) && TextUtils.isEmpty(value))
            return "";

        BigInteger gasPrice = null;
        BigInteger gasLimit = null;

        if (isUseDefault) {
            // Gwei 转 wei 
            gasPrice = BigInteger.valueOf(WalletApp.getInstance().getGasPrice()).multiply(BigInteger.valueOf(1000_000_000));
            gasLimit = BigInteger.valueOf(WalletApp.getInstance().getGasLimit());
        } else {
            gasPrice = BigInteger.valueOf(WalletApp.getInstance().getUserGasPrice());
            gasLimit = BigInteger.valueOf(WalletApp.getInstance().getUserGasLimit());
        }

        long lNonce = WalletApp.getInstance().getNonce();
        BigInteger nonce = BigInteger.valueOf(lNonce);
        WalletApp.getInstance().saveNonce(++lNonce);

        BigInteger realValue;
//        if (record.getUnit() == 0){ //eth
//            realValue = Convert.toWei(value, Convert.Unit.ETHER).toBigInteger();
//        }else if (record.getUnit() == 9){ //Gwei
//            realValue = Convert.toWei(value, Convert.Unit.GWEI).toBigInteger();
//        }else{
//            realValue = Convert.toWei(value, Convert.Unit.ETHER).toBigInteger();
//        }


        realValue = ToMinUtitUtils.ethConvertToMin(record.getUnit(), value);

        signText = wallet.signedEthTransactionData(to, nonce, gasPrice, gasLimit, realValue, "");
        return signText;
    }

    //检验地址  //弃用
    private boolean checkAddress(String address) {

        int type = wallet.getType();
        if (type == CoinWallet.TYPE_BIT_COIN) {
            //btc地址校验
            if (address.startsWith("1") || address.startsWith("3") || address.startsWith("5")) {

            } else {
                ToastUtils.showToast("地址" + address + "有误");
                return false;
            }

        } else if (type == CoinWallet.TYPE_ETH_COIN) {
            //eth地址校验
            if (!address.startsWith("0x") && !address.startsWith("0X")) {
                ToastUtils.showToast("地址" + address + "有误");
                return false;
            }

        } else if (type == 2) {
            //待补充
            return true;
        } else if (type == CoinWallet.TYPE_LTC_COIN) {
            //
            return true;
        } else if (type == CoinWallet.TYPE_BCH_COIN) {
            //
            return true;
        } else if (type == CoinWallet.TYPE_EOS_COIN) {
            //
            return true;
        } else {
            return false;
        }

        return true;
    }


}
       